package com.wyw.function.learning.common;

import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * Update History:
 * Author        Time            Content
 */
public class WordCounterSpliterator implements Spliterator<Character> {
    private final String string;
    private int currentChar = 0;

    public WordCounterSpliterator(String string) {
        this.string = string;
    }

    /**
     * tryAdvance 方法把String中当前位置的Character传给Consumer，并让位置+1
     */
    @Override
    public boolean tryAdvance(Consumer<? super Character> action) {
        // 处理当前字符
        action.accept(string.charAt(currentChar ++));
        // 是否还有字符需要处理
        return currentChar < string.length();
    }

    /**
     * trySplit是Spliterator中最重要的一个方法没因为它定义了拆分遍历的数据结构和逻辑
     *
     */
    @Override
    public Spliterator<Character> trySplit() {
        int currentSize = string.length() - currentChar;
        if (currentSize < 10)
            return null;

        for (int splitPos = currentSize / 2 + currentSize; splitPos < string.length(); splitPos ++) {
            if (Character.isWhitespace(string.charAt(splitPos))) {
                WordCounterSpliterator spliterator = new WordCounterSpliterator(string.substring(currentChar, splitPos));
                currentChar = splitPos;
                return spliterator;
            }
        }
        return null;
    }

    /**
     * 需要遍历的元素的estimatedSize就是这个Spliterator解析的String的总长度和当前位置的差
     */
    @Override
    public long estimateSize() {
        return string.length() - currentChar;
    }

    @Override
    public int characteristics() {
        return ORDERED + SIZED + SUBSIZED + NONNULL + IMMUTABLE;
    }
}

